package com.gjp.processdemo.config.flowable;

import com.google.common.collect.Lists;
import org.flowable.idm.api.Group;
import org.flowable.idm.api.IdmIdentityService;
import org.flowable.ui.common.model.RemoteGroup;
import org.flowable.ui.common.model.RemoteToken;
import org.flowable.ui.common.model.RemoteUser;
import org.flowable.ui.common.service.idm.RemoteIdmService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 解决设计器中编辑流程图时，筛选用户和组报错的问题
 *
 * @author 郭金鹏
 * @date 2019-12-20 11:06:35
 */
@Service
@Primary
public class CustomRemoteIdmServiceImpl implements RemoteIdmService {
    @Autowired
    private IdmIdentityService idmIdentityService;

    @Override
    public RemoteUser authenticateUser(String username, String password) {
        return null;
    }

    @Override
    public RemoteToken getToken(String tokenValue) {
        return null;
    }

    @Override
    public RemoteUser getUser(String userId) {
        return null;
    }

    @Override
    public List<RemoteUser> findUsersByNameFilter(String filter) {
        if (StringUtils.isEmpty(filter)) {
            return Lists.newArrayList();
        }
        List<RemoteUser> collect = idmIdentityService
                .createUserQuery()
                .userLastNameLike("%" + filter + "%")
                .list()
                .stream()
                .map(item -> {
                    RemoteUser remoteUser = new RemoteUser();
                    BeanUtils.copyProperties(item, remoteUser);
                    return remoteUser;
                }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<RemoteUser> findUsersByGroup(String groupId) {
        return null;
    }

    @Override
    public RemoteGroup getGroup(String groupId) {
        Group group = idmIdentityService.createGroupQuery().groupId(groupId).singleResult();
        return new RemoteGroup(group.getId(), group.getName());
    }

    @Override
    public List<RemoteGroup> findGroupsByNameFilter(String filter) {
        if (StringUtils.isEmpty(filter)) {
            return Lists.newArrayList();
        }
        List<RemoteGroup> collect = idmIdentityService
                .createGroupQuery()
                .groupNameLike("%" + filter + "%")
                .list()
                .stream()
                .map(item -> {
                    RemoteGroup remoteGroup = new RemoteGroup();
                    BeanUtils.copyProperties(item, remoteGroup);
                    return remoteGroup;
                }).collect(Collectors.toList());
        return collect;
    }
}
